package com.besttone.locate;

import java.io.IOException;
import java.io.StringReader;
import java.util.List;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import com.besttone.locate.model.PosInfoModel;
import com.besttone.locate.util.GPSUtil;
import com.besttone.locate.util.LocateUtil;
import com.besttone.locate.util.PosInfoHandler;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class LocationActivity extends Activity {
    private static final String TAG = "Locate";
    private EditText field_phone;
    private Button button_query;
    private TextView view_result;
    private ProgressDialog dialog;
	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        findViews();
        setListensers();
    }
    
    private void findViews() {
    	try {
			field_phone = (EditText)findViewById(R.id.phone);
			button_query = (Button)findViewById(R.id.query);
			view_result = (TextView)findViewById(R.id.result);
		} catch (Exception e) {
			e.printStackTrace();
			Log.e(TAG, "error" + e.toString());
			Toast.makeText(LocationActivity.this,R.string.error,Toast.LENGTH_SHORT).show();
		}
    }
    
    private void setListensers() {
    	button_query.setOnClickListener(queryLocation);
    }
    
    private Button.OnClickListener queryLocation = new Button.OnClickListener() {
    	public void onClick(View v) {
    		//清除焦点
			field_phone.clearFocus();
			//隐藏键盘
			hideInput(field_phone);
    		String phone = field_phone.getText().toString().trim();
    		LocateUtil util = new LocateUtil();
    		String rtnXml = null;
    		if(checkLength(phone)){
        		if(checkCNet(phone)){
            		try {
        				rtnXml = util.getMobileLocateInfo(phone);
        			} catch (Exception e) {
        				e.printStackTrace();
        			}
        			if(rtnXml==null || "".equals(rtnXml.trim())){
        				Toast.makeText(LocationActivity.this, "粗定位接口异常", Toast.LENGTH_SHORT).show();
        			} else {
        				dealResult(rtnXml);
        			}
        		} else {
        			field_phone.setText("");
        			Toast.makeText(LocationActivity.this, "请输入C网手机号码", Toast.LENGTH_SHORT).show();
        		}
    		} else {
    			Toast.makeText(LocationActivity.this, "手机号码长度为11位", Toast.LENGTH_SHORT).show();
    		}


    	}
    };
    
    public void dealResult(String rtnXml) {
    	PosInfoModel posInfo = null;
    	SAXParserFactory factory = SAXParserFactory.newInstance();
    	
    	try {
			SAXParser parser = factory.newSAXParser();
			XMLReader xmlReader = parser.getXMLReader();
			PosInfoHandler handler = new PosInfoHandler();
			xmlReader.setContentHandler(handler);
			StringReader sr = new StringReader(rtnXml);
			InputSource is = new InputSource(sr);
			xmlReader.parse(is);
			posInfo = handler.getPosInfo();
			if(posInfo!=null && posInfo.isErrorFlag()==true){
				Toast.makeText(LocationActivity.this, "暂时无法获取手机位置信息，请稍后再试", Toast.LENGTH_SHORT).show();
			} else {
				//显示loading进度
//        		showDialog(DIALOG2_KEY);
//				StringBuffer sb = new StringBuffer("http://ditu.google.cn/maps?hl=zh-CN&mrt=loc&q=");
//				sb.append(posInfo.getLATITUDE());
//				sb.append(",");
//				sb.append(posInfo.getLONGITUDE());
//				String url = sb.toString();
//				Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
//				startActivity(intent);
				/*
				double lat= Double.parseDouble(posInfo.getLATITUDE());
				double lon = Double.parseDouble(posInfo.getLONGITUDE());
				Log.e(TAG, "error纠偏后" + GPSUtil.adjustLoction(lon, lat));*/
				
				/** 调用google map
				StringBuffer sb = new StringBuffer("http://ditu.google.cn/maps?hl=zh-CN&mrt=loc&q=");
				sb.append(posInfo.getLATITUDE());
				sb.append(",");
				sb.append(posInfo.getLONGITUDE());
				String url = sb.toString();
				Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
						          & Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
				intent.setClassName("com.google.android.apps.maps",
						          "com.google.android.maps.MapsActivity");
				startActivity(intent);
				**/
				
				/**
				 * 调用本地百度地图
				 */
				
				Intent intent = new Intent();
				intent.setClass(LocationActivity.this, BMapActivity.class);
				Bundle bundle = new Bundle();
				bundle.putString("lng", posInfo.getLONGITUDE());
				bundle.putString("lat", posInfo.getLATITUDE());
				intent.putExtras(bundle);
				startActivity(intent);
			}
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
    
    protected static final int MENU_ABOUT = Menu.FIRST;
    protected static final int MENU_Quit = Menu.FIRST+1;
    
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, MENU_ABOUT, 0, " 关于 ...");
		menu.add(0, MENU_Quit, 0, " 结束 ");
		return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		switch (item.getItemId()) {
		case MENU_ABOUT:
			openOptionsDialog();
			break;
		case MENU_Quit:
			showExitAlert();
			break;
		}
		return true;
		}
	
	private void openOptionsDialog() { 
		new AlertDialog.Builder(LocationActivity.this)
		.setTitle(R.string.about_title)
		.setMessage(R.string.about_msg)
		.setPositiveButton(R.string.confirm,
				new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialoginterface, int i) {}
				})
		.setNegativeButton(R.string.homepage_label,
				new DialogInterface.OnClickListener(){
						public void onClick(DialogInterface dialoginterface, int i){
							//go to url
							Uri uri = Uri.parse(getString(R.string.homepage_uri));
							Intent intent = new Intent(Intent.ACTION_VIEW, uri);
							startActivity(intent);
						}
				})
		   .show();
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// 按下键盘上返回按钮
		if(keyCode == KeyEvent.KEYCODE_BACK ){
			showExitAlert();
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}
	
	private void showExitAlert() {
        new AlertDialog.Builder(this)
        .setTitle(R.string.prompt)
        .setMessage(R.string.quit_desc)
        .setNegativeButton(R.string.cancel,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                            int which) {}
                })
        .setPositiveButton(R.string.confirm,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                            int whichButton) {
                    	exitApp();
                    }
                }).show();
	}
	
	//彻底关闭程序
	protected void exitApp() {
	    super.onDestroy();
	    System.exit(0);
	    // 或者下面这种方式
	    // android.os.Process.killProcess(android.os.Process.myPid());
	}
	
    private static final int DIALOG1_KEY = 0;
    private static final int DIALOG2_KEY = 1;
	
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DIALOG1_KEY: {
            	dialog = new ProgressDialog(this);
                dialog.setTitle(null);
                dialog.setMessage("正在定位，请稍候...");
                dialog.setIndeterminate(true);
                dialog.setCancelable(true);
                return dialog;
            }
            case DIALOG2_KEY: {
            	dialog = new ProgressDialog(this);
                dialog.setMessage("正在定位，请稍候...");
                dialog.setIndeterminate(true);
                dialog.setCancelable(true);
                return dialog;
            }
        }
        return null;
    }
    
    @Override
    protected void onStop() {
    	//dialog.dismiss();
    	super.onResume();
    }
    
    public int showMap() {
        PackageManager packageManager = this.getPackageManager();
        List<ApplicationInfo> packs = packageManager
                        .getInstalledApplications(PackageManager.GET_ACTIVITIES);

        for (ApplicationInfo packageInfo : packs) {
                if (packageInfo.packageName.equals("com.google.android.apps.maps")) {
                        return 1;
                }
        }

        for (ApplicationInfo packageInfo : packs) {
                if (packageInfo.packageName.equals("brut.googlemaps")) {
                        return 2;
                }
        }

        for (ApplicationInfo packageInfo : packs) {
                if (packageInfo.packageName.equals("com.autonavi.minimap")) {
                        return 3;
                }
        }

        return 4;
    }
    
    /**
     * 隐藏软键盘
     */
    private void hideInput(EditText editText){
    	InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
    	imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
    }
    
    /**
     * 校验手机号码长度
     * @param phone
     * @return
     */
    public boolean checkLength(String phone) {
    	if(phone!=null && !"".equals(phone) && phone.length()==11){
    		return true;
    	} else {
    		return false;
    	}
    }
    
    /**
     * 校验手机号码是否是C网
     * @param phone
     * @return
     */
	public boolean checkCNet(String phone) {
		String pattern = "^0{0,1}(133|150|153|180|181|189)[0-9]{8}$";
		Pattern p = Pattern.compile(pattern);
		Matcher m = p.matcher(phone);
		return m.matches();
	}
}
